package com.uinnova.product.eam.web.bm.peer;

import com.binary.core.exception.BinaryException;
import com.binary.core.util.BinaryUtils;
import com.binary.jdbc.Page;
import com.uinnova.product.eam.comm.model.es.EamMultiModelHierarchy;
import com.uinnova.product.eam.comm.model.es.EamMultiModelType;
import com.uinnova.product.eam.model.dto.EamMultiModelHierarchyDto;
import com.uinnova.product.eam.service.IBmHierarchySvc;
import com.uinnova.product.eam.service.IBmMultiModelHierarchySvc;
import com.uinnova.project.base.diagram.util.FileFilterUtil;
import com.uino.util.rsm.RsmUtils;
import com.uino.util.sys.SysUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;

/**
 * 多模型层级
 *
 * @author zdh_c
 */
@Service
@Slf4j
public class BmMultiModelHierarchyPeer {

    @Resource
    IBmMultiModelHierarchySvc multiModelHierarchySvc;

    @Autowired
    private RsmUtils rsmUtils;

    @Value("${local.resource.space}")
    private String localPath;

    @Value("${http.resource.space}")
    private String httpPath;

    @Resource
    IBmHierarchySvc bmHierarchySvc;


    public Page<EamMultiModelHierarchy> queryList(Integer pageNum, Integer pageSize, String like,Integer releaseState, Integer modelType) {
        return multiModelHierarchySvc.queryList(pageNum, pageSize, like,releaseState, modelType);
    }

    public Long saveOrUpdate(EamMultiModelHierarchyDto multiModelHierarchy) {
        if (BinaryUtils.isEmpty(multiModelHierarchy.getName()) /*|| BinaryUtils.isEmpty(multiModelHierarchy.getModelType())*/) {
            throw new BinaryException("模型工艺必填项不能为空");
        }
        return multiModelHierarchySvc.saveOrUpdate(multiModelHierarchy);
    }

    public Collection<EamMultiModelType> queryModelTypeList() {
        return multiModelHierarchySvc.queryModelTypeList();
    }

    public Integer saveModelType(List<EamMultiModelType> modelTypeList) {
        return multiModelHierarchySvc.saveModelType(modelTypeList);
    }

    public Integer deleteModelType(Long id) {
        return multiModelHierarchySvc.deleteModelType(id);
    }

    public Long releaseModel(Long modelId) {
        return multiModelHierarchySvc.releaseModel(modelId);
    }

    public Long cancelReleaseModel(Long modelId) {
        return multiModelHierarchySvc.cancelReleaseModel(modelId);
    }

    public Integer deleteModel(Long modelId) {
       return multiModelHierarchySvc.deleteModel(modelId);
    }

    public EamMultiModelHierarchy getModelById(Long id) {
        return multiModelHierarchySvc.getModelById(id);
    }

    public Integer copeModel(Long id) {
        return multiModelHierarchySvc.copeModel(id);
    }

    public Integer flashModuleData() {
        return multiModelHierarchySvc.flashModuleData();
    }

    public void uploadPictures(MultipartFile file) {
        // 同一租户上传一个目录下
        String path = "/multiModel/" + SysUtil.getCurrentUserInfo().getDomainId();
        File destFolder = new File(FileFilterUtil.parseFilePath(localPath + path));
        if (!destFolder.exists()) {
            destFolder.mkdirs();
        }
        String docName = Objects.requireNonNull(file.getOriginalFilename()).substring(0, file.getOriginalFilename().lastIndexOf("."));
        String fileType = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
        String destFileName = System.currentTimeMillis()+"." + fileType;
        File destFile = new File(destFolder, destFileName);
        try {
            file.transferTo(new File(destFile.getCanonicalPath()));
            rsmUtils.uploadRsmFromFile(new File(destFile.getCanonicalPath()));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public Map<String, Object> pictureList() {

        // 获取文件夹录路径
        String path = localPath + "/multiModel";
        List<String> fileNameList = new ArrayList<>();
        // 创建File对象
        // 获取租户下上传图片
        String pathDomain = path + "/" + SysUtil.getCurrentUserInfo().getDomainId();
        File fileDomain = new File(FileFilterUtil.parseFilePath(pathDomain));
        if (fileDomain.exists()) {
            File[] files = fileDomain.listFiles();
            if (files != null) {
                for (File file : files) {
                    if (file.isFile()) {
                        fileNameList.add(file.getName());
                    }
                }
            }
        }
        if (!CollectionUtils.isEmpty(fileNameList)) {
            // 封装返回参数
            fileNameList.sort(Comparator.naturalOrder());
        }
        Map<String, Object> result = new HashMap<>(2);
        result.put("httpPath", httpPath+"/multiModel/"+SysUtil.getCurrentUserInfo().getDomainId());
        result.put("pictureList", fileNameList);
        return result;
    }

    public void removePicture(String name) {
        // 校验图片是否被使用
        if (BinaryUtils.isEmpty(name)) {
            throw new BinaryException("图片名称不可为空");
        }
        if (bmHierarchySvc.checkPictureUse(name)) {
            throw new BinaryException("该引导页已被使用");
        }
        // 指定文件夹路径和要删除的文件名
        String folderPath = FileFilterUtil.parseFilePath(localPath + "/multiModel");
        // 创建Path对象
        Path filePath = Paths.get(folderPath, name);
        if (!Files.exists(filePath)) {
            String path = folderPath+"/" + SysUtil.getCurrentUserInfo().getDomainId();
            filePath = Paths.get(FileFilterUtil.parseFilePath(path), name);
            if (!Files.exists(filePath)) {
                throw new BinaryException("图片不存在");
            }
        }
        try {
            Files.delete(filePath);
            log.info("建模工艺图片删除成功:"+name);
        } catch (IOException e) {
            log.error("文件删除失败：" + e.getMessage());
        }
    }
}
